# ip_reporter_server.py
from flask import Flask, request, jsonify, render_template
from datetime import datetime
import os

app = Flask(__name__)

# 存储设备信息的字典 {设备ID: {ip, last_seen, device_name}}
devices = {}

@app.route('/report', methods=['POST'])
def report_ip():
    """接收客户端上报的IP地址"""
    data = request.json
    
    # 验证必要字段
    if not data or 'device_id' not in data or 'ip' not in data:
        return jsonify({'status': 'error', 'message': 'Missing required fields'}), 400
    
    device_id = data['device_id']
    ip_address = data['ip']
    device_name = data.get('device_name', 'Unknown Device')
    
    # 更新设备信息
    devices[device_id] = {
        'ip': ip_address,
        'last_seen': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'device_name': device_name
    }
    
    print(f"[{datetime.now()}] 设备上报: {device_name} ({device_id}) -> {ip_address}")
    return jsonify({'status': 'success', 'message': 'IP reported'})

@app.route('/devices', methods=['GET'])
def list_devices():
    """列出所有注册的设备"""
    return jsonify(devices)

@app.route('/')
def dashboard():
    """设备管理面板"""
    return render_template('dashboard.html', devices=devices)

if __name__ == '__main__':
    # 创建存储日志的目录
    os.makedirs('logs', exist_ok=True)
    
    # 启动服务器
    app.run(host='0.0.0.0', port=5000, debug=True)